package com.frogs.ucenter.v1.service.insurance.zhongan;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.SexEnum;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.ucenter.entity.InsuranceInfo;
import com.frogs.ucenter.entity.InsuranceRecord;
import com.frogs.ucenter.entity.PartnerInsuranceRecord;
import com.frogs.ucenter.openplatform.util.ZhonganHttpsConnectUtil;
import com.frogs.ucenter.v1.request.InsuranceRecordAddRequest;
import com.frogs.ucenter.v1.service.insurance.base.PartnerInsuranceCompanyBaseService;
import com.frogs.ucenter.v1.util.ApiConstants;

/**
 * 众安保险业务逻辑处理类
 *
 * @author wushubin
 */
@Service(ApiConstants.VERSION+"zhonganService")
public class ZhonganServiceImpl extends PartnerInsuranceCompanyBaseService {

	private static final Logger log = LoggerFactory.getLogger(ZhonganServiceImpl.class);

	@Override
	public PartnerInsuranceRecord add(InsuranceRecordAddRequest addRequest,InsuranceInfo insuranceInfo,InsuranceRecord record) {
		try{
			//1.创建投保人
			JSONObject bizContent = this.addUser(addRequest, insuranceInfo);
			String partnerUserId =  bizContent.get("userId").toString();
			//2.同步保单信息到合作方
			//注意众安的意外险需要提交2次保单，骨折险只需要1次保单
			return this.addInsuranceRecord(insuranceInfo, record, partnerUserId) ;
		}
		catch(Exception e){
			log.error("func[add] addRequest[{}] insuranceInfo [{}] insuranceRecord[{}] exception[{} - {}] desc[fail]",
					new Object[] { JSON.toJSONString(addRequest),JSON.toJSONString(insuranceInfo) ,
					JSON.toJSONString(record), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
			
			PartnerInsuranceRecord partnerInsuranceRecord = new PartnerInsuranceRecord();
			partnerInsuranceRecord.setCode(ApiResultEnum.FAIL.getId());
			partnerInsuranceRecord.setTip("同步众安保单信息时，出现异常");
			return partnerInsuranceRecord;
		}
	}
	
	private PartnerInsuranceRecord addInsuranceRecord(InsuranceInfo insuranceInfo,InsuranceRecord record , String partnerUserId) throws Exception{
		
		Map<String, Object> map = new HashMap<String,Object>();
		
		map.put("policyHolderUserId",partnerUserId);
		map.put("insuredUserId",partnerUserId );
		map.put("beneficiaryUserId",partnerUserId);
		map.put("channelOrderNo",record.getChannelOrderNo() );
		map.put("premium","0" );
		
		map.put("policyBeginDate", DateUtil.formatDate(DateUtil.getDateAfterDays(new Date(), 1), "yyyyMMdd000000"));
		map.put("policyEndDate",DateUtil.formatDate(super.getDateAfterDays(new Date(), insuranceInfo.getValidDate(),insuranceInfo.getValidDateUnit()) ,"yyyyMMdd235959"));
		map.put("insureDate", DateUtil.formatDate(DateUtil.getDateAfterDays(new Date(), 1), "yyyyMMddHHmmss"));
		map.put("payType", "3");//默认3即可
		map.put("channelId",insuranceInfo.getChannelId().toString() );
		map.put("productId",insuranceInfo.getProductId().toString() );
		//map.put("extraInfo", );
		JSONObject result = ZhonganHttpsConnectUtil.addPolicy(map);
		PartnerInsuranceRecord partnerInsuranceRecord = new PartnerInsuranceRecord();
		if(StringUtil.isEmpty(result.get("bizContent"))){
			//如果创建保单失败，则返回失败状态
			partnerInsuranceRecord.setCode(ApiResultEnum.FAIL.getId());
			partnerInsuranceRecord.setTip(result.getString("errorMsg"));
		}
		else{
			JSONObject bizContent = (JSONObject)result.get("bizContent");
			//如果创建保单失败，则返回失败状态
			if(bizContent.get("policyNo") == null){
				partnerInsuranceRecord.setCode(ApiResultEnum.FAIL.getId());
				partnerInsuranceRecord.setTip(bizContent.getString("errorMsg"));
			}else{
				/**
				 * 注意：意外伤害保险 需要提交多一次，骨折险就不用
				 * 10122营运交通工具乘客意外伤害保险（用于前台展现）
				 * 10123 私家车驾驶人员意外伤害保险
				 */
				if(insuranceInfo.getProductId() == 10122){
					map.put("channelOrderNo",record.getChannelOrderNo()+"-2" );
					map.put("productId","10123");
					result = ZhonganHttpsConnectUtil.addPolicy(map);
				}
				partnerInsuranceRecord.setCode(ApiResultEnum.SUCCESS.getId());
				partnerInsuranceRecord.setPolicyBeginDate(DateUtil.parseDate(bizContent.getString("policyBeginDate"),"yyyyMMddHHmmss"));
				partnerInsuranceRecord.setPolicyEndDate(DateUtil.parseDate(bizContent.getString("policyEndDate"),"yyyyMMddHHmmss"));
				partnerInsuranceRecord.setPolicyId(bizContent.getInteger("policyId"));
				partnerInsuranceRecord.setPolicyNo(bizContent.getString("policyNo"));
				partnerInsuranceRecord.setPremium(bizContent.getDouble("premium"));
			}
		}
		return partnerInsuranceRecord;
	}
	
	private JSONObject addUser(InsuranceRecordAddRequest addRequest,InsuranceInfo insuranceInfo) throws Exception{
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("userName",addRequest.getName() );
		map.put("sex", addRequest.getSex() == SexEnum.MALE.getId() ? "M":"F" );
		map.put("email",addRequest.getEmail() );
		map.put("mobilePhone",addRequest.getPhone() );
		map.put("identityNo",addRequest.getIdentityCard() );
		map.put("channelId",insuranceInfo.getChannelId().toString() );
		map.put("channelUserNo",insuranceInfo.getCompanyId()+"-"+new Date().getTime() );
		
		JSONObject user = ZhonganHttpsConnectUtil.addByChannel(map);
		JSONObject bizContent = (JSONObject)user.get("bizContent");
		return bizContent;
	}

	@Override
	public JSONObject quit(InsuranceInfo insuranceInfo , InsuranceRecord record) throws Exception {
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("policyNo", record.getPolicyNo());
		map.put("channelId",insuranceInfo.getChannelId() );
		map.put("productId", insuranceInfo.getProductId());
		
		return ZhonganHttpsConnectUtil.quitPolicy(map);
	}

	

}
